#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080
#define BUFFER_SIZE 1024

int main()
{
    int sock;
    struct sockaddr_in server_address;
    char buffer[BUFFER_SIZE] = {0};

    // 创建socket文件描述符
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 设置服务器地址
    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(PORT);
    server_address.sin_addr.s_addr = inet_addr("127.0.0.1");

    // 连接到服务器
    if (connect(sock, (struct sockaddr *)&server_address, sizeof(server_address)) < 0)
    {
        perror("connection to server failed");
        exit(EXIT_FAILURE);
    }

    printf("Connected to server.\n");

    // 发送数据
    printf("Enter numbers (end with 0): \n");
    while (1)
    {
        int num;
        scanf("%d", &num);
        if (num == 0)
        {
            break;
        }

        char num_str[10];
        snprintf(num_str, sizeof(num_str), "%d", num);
        send(sock, num_str, strlen(num_str), 0);
    }

    // 发送结束标志
    send(sock, "0", 1, 0);

    // 接收服务器返回的结果
    int n = read(sock, buffer, BUFFER_SIZE);
    if (n > 0)
    {
        printf("Sum from server: %s\n", buffer);
    }

    // 关闭socket
    close(sock);

    return 0;
}